/*
    Copyright  Louis CHEREL cherel.louis@gmail.com  
    This file is part of Agenda de l'Efrei.

    Agenda de l'Efrei is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Agenda de l'Efrei is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Agenda de l'Efrei.  If not, see <http://www.gnu.org/licenses/>.
 */

package fr.efrei.AgendaEfrei;

import android.app.*;
import android.app.ActionBar.OnNavigationListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.*;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.*;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Toast;
import java.util.GregorianCalendar;

public class MainActivity extends Activity implements OnNavigationListener{//,OnMenuVisibilityListener {
    
    //globals
    protected SharedPreferences sharedPref;
    protected String mPromo;
    protected String mDay="1";
    protected String mDayName;
    protected String mModeAffichage="0";
    protected boolean mIsShowButtonsPossible=false;
    protected boolean mIsButtonsShown=true;
    private   View buttonLayout=null;
    protected boolean mWasPaused=false;
    protected boolean mRefreshWeek=false;
    protected String[] mWeekNames = new String[5];
    protected String[] mWeekIndices = new String[5];
    protected int mCurrentWeek=0;
    protected MenuItem mProgressbar=null;
    protected String mUrl = "";
    protected String mUrlBase = "http://edt.bde.assos.efrei.fr/?";
    protected long mLastUpdate;
    private ActionBar mActionbar;
    private WebView mWebview;
    private Button mPrevbutton=null;
    protected static boolean isWeeksUpdaterLaunched=false ;
    protected static boolean isFileManagerLaunched=false ;
    protected static boolean isMainActivityShown=false ;
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {   // print the action bar
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.actionbar_menu, menu);
        mProgressbar = menu.findItem(R.id.reload);
        return true;
    }
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    
    @Override
    public void onResume()
    {
        super.onResume();
        sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        boolean notesDemarrage = sharedPref.getBoolean(getString(R.string.pref_notes_demarrage_KEY), false);
        if(!notesDemarrage || getIsMainActivityShown()){
            getPromo();
            mActionbar = getActionBar(); // used to interact with the Action Bar
            mActionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

            getWebview();
            
            if(!mWasPaused)
            {
                readWeeks();
                getDate();
                // savoir si on doit changer le spinner des dates, quand on tourne l'écran
                mRefreshWeek=false;
                // on nettoie les anciens fichiers
                new FileManager(mPromo,mDay,mWeekIndices[mCurrentWeek],false,false,this).execute();
            }
            else{
                mActionbar.setTitle(mDayName);
                mRefreshWeek=true;
            }
            if(findViewById(R.id.lundi_b)!=null)
            {
                onTabLoad();
            }

            loadPage();
        }
        else{
            Intent intent_notes = new Intent(this, ViewNotes.class);
            startActivity(intent_notes);
        }
    }
    
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if(hasFocus){
            if(mRefreshWeek){
                Log.v("onWindowFocusChanged", "mRefresh");
                ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this, R.layout.spinner, mWeekNames);
                mActionbar.setListNavigationCallbacks(adapter,(OnNavigationListener)this);
                mActionbar.setSelectedNavigationItem(mCurrentWeek);
                mRefreshWeek=false;
            }
            
            
            if(!mIsShowButtonsPossible && findViewById(R.id.lundi)==null && buttonLayout==null){
                buttonLayout = findViewById(R.id.days_menu);
                mIsShowButtonsPossible=true;
                if(mModeAffichage.equals("1") || mIsButtonsShown==false)
                {
                    if(buttonLayout!=null)
                        buttonLayout.setVisibility(View.GONE);
                    mIsButtonsShown=false;
                }
            }
            else if(findViewById(R.id.lundi)==null){
                if(mIsButtonsShown==false)
                {
                    buttonLayout.setVisibility(View.GONE);
                }
                else{
                    buttonLayout.setVisibility(View.VISIBLE);
                }
            }
        }
    }
    
    
    public void loadPage()
    {
        new FileManager(mPromo,mDay,mWeekIndices[mCurrentWeek],true,false,this).execute(mWebview,mProgressbar);
    }
    
    public void loadPage(boolean isRefresh)
    {
        Toast toast = Toast.makeText(this, "Page mise à jour.", Toast.LENGTH_SHORT);
        new FileManager(mPromo,mDay,mWeekIndices[mCurrentWeek],true,isRefresh,this).execute(mWebview,mProgressbar,toast);
    }
    
    public void onTabClick(MenuItem item)
    {
        if(item.getTitle().equals("Rafraichir")==false){
            mActionbar.setTitle(item.getTitle());
        }
        if(item.getTitle().equals("Lundi")) {
            mDayName="Lundi";
            mDay="1";
            loadPage();
        }
        else if(item.getTitle().equals("Mardi")) {
            mDayName="Mardi";
            mDay="2";
            loadPage();
        }
        else if(item.getTitle().equals("Mercredi")) {
            mDayName="Mercredi";
            mDay="3";
            loadPage();
        }
        else if(item.getTitle().equals("Jeudi")) {
            mDayName="Jeudi";
            mDay="4";
            loadPage();
        }
        else if(item.getTitle().equals("Vendredi")) {
            mDayName="Vendredi";
            mDay="5";
            loadPage();
        }
        else if(item.getTitle().equals("Samedi")) {
            mDayName="Samedi";
            mDay="6";
            loadPage();
        }
        else if(item.getTitle().equals("Semaine complète")) {
            mDayName="Semaine complète";
            if(findViewById(R.id.lundi_b)!=null)
            {
                if(mPrevbutton!=null) {
                    mPrevbutton.setTypeface(Typeface.DEFAULT);
                }
            }
            mDay="-1";
            loadPage();
        }
        else if(item.getTitle().equals("Préférences")) {
            Intent intent_preferences = new Intent(this, Preferences.class);
            startActivity(intent_preferences);
            getPromo();
            getDate();
            loadPage();
        }
        else if(item.getTitle().equals("Crédits")) {
            Intent intent_credits = new Intent(this, Credits.class);
            startActivity(intent_credits);
        }
        else if(item.getTitle().equals("Rafraichir")) {
            loadPage(true);
        }
        else if(item.getTitle().equals("Voir vos notes"))
        {
            Intent intent_notes = new Intent(this, ViewNotes.class);
            startActivity(intent_notes);
        }
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==android.R.id.home){
            if(findViewById(R.id.lundi)==null){
                if(buttonLayout.getVisibility()==View.GONE) {
                    buttonLayout.setVisibility(View.VISIBLE);
                    mIsButtonsShown=true;
                }
                else{
                    buttonLayout.setVisibility(View.GONE);
                    mIsButtonsShown=false;
                }
            }
            return true;
        }
        else{
            return super.onOptionsItemSelected(item);
        }
    }
    
    public void onTabClick(View view)
    {
        Button button = (Button)view;
        
        mActionbar.setTitle(button.getText());
        if(mPrevbutton!=null) {
            mPrevbutton.setTypeface(Typeface.DEFAULT);
        }
        
        button.setTypeface(button.getTypeface(),Typeface.BOLD);
        
        mPrevbutton = button;
        
        switch(view.getId())
        {
            case R.id.lundi_b:
                mDayName="Lundi";
                mDay="1";
                loadPage();
                break;
            
            case R.id.mardi_b:
                mDayName="Mardi";
                mDay="2";
                loadPage();
                break;
            
            case R.id.mercredi_b:
                mDayName="Mercredi";
                mDay="3";
                loadPage();
                break;
            
            case R.id.jeudi_b:
                mDayName="Jeudi";
                mDay="4";
                loadPage();
                break;
            
            case R.id.vendredi_b:
                mDayName="Vendredi";
                mDay="5";
                loadPage();
                break;
            
            case R.id.samedi_b:
                mDayName="Samedi";
                mDay="6";
                loadPage();
                break;
        }
    }
    
    public void onTabLoad()
    {
        Button button;
        switch(Integer.parseInt(mDay))
        {
            case 1:
                button = (Button)findViewById(R.id.lundi_b);
                break;
            
            case 2:
                button = (Button)findViewById(R.id.mardi_b);
                break;
            
            case 3:
                button = (Button)findViewById(R.id.mercredi_b);
                break;
            
            case 4:
                button = (Button)findViewById(R.id.jeudi_b);
                break;
            
            case 5:
                button = (Button)findViewById(R.id.vendredi_b);
                break;
            
            case 6:
                button = (Button)findViewById(R.id.samedi_b);
                break;
            default:
                button = null;
                break;
        }
        
        
        if(mPrevbutton!=null) {
            mPrevbutton.setTypeface(Typeface.DEFAULT);
        }
        if(button!=null)
        {
            button.setTypeface(button.getTypeface(),Typeface.BOLD);
            mActionbar.setTitle(button.getText());
        }
        else{
            mActionbar.setTitle(mDayName);
        }
        mPrevbutton = button;
    }
    
    public void getWebview(){
        mWebview = (WebView) findViewById(R.id.page);
        WebSettings mWebview_settings = mWebview.getSettings();
        mWebview_settings.setBuiltInZoomControls(true);
        mWebview_settings.setUseWideViewPort(true);
    }
    
    public void getDate(){
        
        
        GregorianCalendar calendar = new GregorianCalendar();
        mWeekIndices[0]=String.valueOf(calendar.get(GregorianCalendar.WEEK_OF_YEAR));
        switch(calendar.get(GregorianCalendar.DAY_OF_WEEK))
        {
            case GregorianCalendar.MONDAY:
                mDayName="Lundi";
                mDay="1";
                break;
            case GregorianCalendar.TUESDAY:
                mDayName="Mardi";
                mDay="2";
                break;
            case GregorianCalendar.WEDNESDAY:
                mDayName="Mercredi";
                mDay="3";
                break;
            case GregorianCalendar.THURSDAY:
                mDayName="Jeudi";
                mDay="4";
                break;
            case GregorianCalendar.FRIDAY:
                mDayName="Vendredi";
                mDay="5";
                break;
            case GregorianCalendar.SATURDAY:
                if((calendar.get(GregorianCalendar.HOUR_OF_DAY)*60+calendar.get(GregorianCalendar.MINUTE))<1110){
                mDayName="Samedi";
                mDay="6";
                }
                else{
                    mWeekIndices[0]=String.valueOf(calendar.get(GregorianCalendar.WEEK_OF_YEAR)+1);
                    mDayName="Lundi";
                    mDay="1";
                }
                break;
            case GregorianCalendar.SUNDAY:
                mWeekIndices[0]=String.valueOf(calendar.get(GregorianCalendar.WEEK_OF_YEAR)+1);
                mDayName="Demain";
                mDay="1";
                break;
        }
        getModeAffichage();
        if(mModeAffichage.equals("1")){
            mDayName="Semaine complète";
            mDay="-1";
        }
        mCurrentWeek=0;
        mActionbar.setTitle(mDayName);
    }
    
    public boolean onNavigationItemSelected(int position, long itemId) {
        switch(position)
        {
            case 0:
                mCurrentWeek=0;
                loadPage();
                return true;
            case 1:
                mCurrentWeek=1;
                loadPage();
                return true;
            case 2:
                mCurrentWeek=2;
                loadPage();
                return true;
            case 3:
                mCurrentWeek=3;
                loadPage();
                return true;
            case 4:
                mCurrentWeek=4;
                loadPage();
                return true;
            default:
                return false;
        }
        
    }
    
    public void readWeeks(){
        try{
            new WeeksUpdater(this).execute();
            new ReadWeeks(mLastUpdate,mWeekNames,mWeekIndices,this).execute(mActionbar);
        
        } catch(Exception e){
            mWebview.loadData("rWeek "+e.toString(),"text/plain",null);
        }
    }
    
    public static void setIsWeeksUpdaterLaunched(boolean b) {
        isWeeksUpdaterLaunched=b;
        Log.v("WeeksUpdater","started:"+isWeeksUpdaterLaunched);
    }
    
    public static boolean getIsWeeksUpdaterLaunched() {
        return isWeeksUpdaterLaunched;
    }
    
    public static void setIsFileManagerLaunched(boolean b) {
        isFileManagerLaunched=b;
        Log.v("FileManager","started:"+isFileManagerLaunched);
    }
    
    public static boolean getIsFileManagerLaunched() {
        return isFileManagerLaunched;
    }
    
    public static void setIsMainActivityShown(boolean b){
        isMainActivityShown=b;
        Log.v("MainActivity","shown:"+isMainActivityShown);
    }
    
    public static boolean getIsMainActivityShown(){
        return isMainActivityShown;
    }
    
    public void getPromo(){
        mPromo = sharedPref.getString(getString(R.string.pref_promo_KEY), "1");
        
    }
    
    public void getModeAffichage(){
        mModeAffichage = sharedPref.getString(getString(R.string.pref_semaine_KEY), "0");
    }
    
    @Override
    public void onSaveInstanceState(Bundle outState){
        
        outState.putString("current_day",mDay);
        outState.putInt("current_week",mCurrentWeek);
        outState.putStringArray("current_weeks", mWeekIndices);
        outState.putStringArray("week_names", mWeekNames);
        outState.putString("current_day_name", mDayName);
        outState.putBoolean("was_paused",true);
        outState.putBoolean("show_buttons",mIsButtonsShown);
        super.onSaveInstanceState(outState);
    }
    
    @Override
    public void onRestoreInstanceState(Bundle inState){
        super.onRestoreInstanceState(inState);
        mWasPaused = inState.getBoolean("was_paused",false);
        Log.v("MainActivity onRestore", "WasPaused:"+mWasPaused);
        if(mWasPaused)
        {
            mDay = inState.getString("current_day",mDay);
            mCurrentWeek = inState.getInt("current_week");
            mWeekIndices = inState.getStringArray("current_weeks");
            mWeekNames = inState.getStringArray("week_names");
            mDayName = inState.getString("current_day_name", mDayName);
            mIsButtonsShown = inState.getBoolean("show_buttons",mIsButtonsShown);
        }
        
    }
 }
